<template>
    <div class="fillinfo-box">
        <el-form :model="regInfo" label-width="auto" ref="regRuleFormRef">
            <div class="table" >
                <div class="table-row"  >
                    <div class="table-cell">
                        <el-form-item label="学生" >
                            <div style="padding-right: 45px;">{{regInfo.snameC}} ( {{ regInfo.sno }} )</div>
                            <el-link type="warning" :underline="false" @click="openHistory">历史挂号记录</el-link>
                        </el-form-item>
                    </div>
                </div>
                <div class="table-row"  >
                    <div class="table-cell">
                        <el-form-item label="班级" >
                            {{ regInfo.clscode }}
                        </el-form-item>
                    </div>
                </div>
                <div class="table-row"  >
                    <div class="table-cell">
                        <el-form-item label="照片" >
                            <img style="width: 90px; height: 110px;" :src="'http://school.kcisxa.org.cn/StudentPic/'+regInfo.sno+'.jpeg'">
                        </el-form-item>
                    </div>
                </div>
                <div class="table-row"  >
                    <div class="table-cell">
                        <el-form-item label="挂号时间">
                            <el-date-picker
                                v-model="regInfo.sDate"
                                type="datetime"
                                placeholder="挂号时间"
                                format="YYYY-MM-DD HH:mm:ss"
                                value-format="YYYY-MM-DD HH:mm:ss"
                            />
                        </el-form-item>
                    </div>
                </div>

                <!-- 性别 -->
                <div class="table-row"  >
                    <div class="table-cell">
                        <el-form-item label="性别" >
                            {{ regInfo.gender == "1" ? '男' : '女' }}
                        </el-form-item>
                    </div>
                </div>

                <!-- 地点 -->
                <div class="table-row"  >
                    <div class="table-cell">
                        <el-form-item label="地点" prop="places">
                            <el-select placeholder="请选择" v-model="regInfo.place" clearable style="width: 220px">
                                <el-option v-for="item in systemInitStore.places" :label="item.pname" :key="item.pno" :value="item.pno"/>
                            </el-select>
                        </el-form-item>
                    </div>
                </div>

                <!-- 就诊原因 -->
                <div class="table-row"  >
                    <div class="table-cell">
                        <el-form-item label="就诊原因">

                            <el-form-item prop="groups1">
                                <el-select placeholder="请选择" v-model="regInfo.groups1" clearable style="width: 220px" @change="onChange1">
                                    <el-option v-for="item in systemInitStore.groups.children" :label="item.label" :key="item.id" :value="item.id"/>
                                </el-select>
                            </el-form-item>
                        
                            <el-form-item prop="groups2">
                                <el-select placeholder="请选择" v-model="regInfo.groups2" clearable style="width: 220px">
                                    <el-option v-for="item in cItems2" :label="item.label" :key="item.id" :value="item.id"/>
                                </el-select>
                            </el-form-item>

                            <el-form-item prop="groups3" v-if="showcItems">
                                <el-select placeholder="请选择" v-if="showcItems" v-model="regInfo.poNo" clearable style="width: 220px">
                                    <el-option v-for="item in systemInitStore.positions" :label="item.poName" :key="item.poNo" :value="item.poNo"/>
                                </el-select>
                            </el-form-item>

                        </el-form-item>
                    </div>
                </div>

                <!-- 处理方式 -->
                <div class="table-row"  >
                    <div class="table-cell">
                        <el-form-item label="处理方式" prop="ways">
                            <el-checkbox-group v-model="regInfo.ways" @change="onCheckWays">
                                <el-checkbox v-for="item in systemInitStore.ways" :key="item.wayNo" :label="item.wayName" :value="item.wayNo">
                                    {{ item.wayName }}
                                </el-checkbox>
                            </el-checkbox-group>
                        </el-form-item>
                    </div>
                </div>

                <!-- 带离时间 -->
                <div class="table-row" v-if="isTake">
                    <div class="table-cell">
                        <el-form-item label="带离时间">
                            <el-date-picker
                                v-model="regInfo.takeDate"
                                type="datetime"
                                placeholder="带离时间"
                                format="YYYY-MM-DD HH:mm:ss"
                                value-format="YYYY-MM-DD HH:mm:ss"
                            />
                        </el-form-item>
                    </div>
                </div>

                <!-- 意外伤害原因 -->
                <div class="table-row"  >
                    <div class="table-cell">
                        <el-form-item label="意外伤害原因" prop="causes">
                            <el-select placeholder="请选择" v-model="regInfo.causeNo" clearable style="width: 220px">
                                <el-option v-for="item in systemInitStore.causes" :label="item.cname" :key="item.cno" :value="item.cno"/>
                            </el-select>
                        </el-form-item>
                    </div>
                </div>

                <!-- 备注 -->
                <div class="table-row"  >
                    <div class="table-cell">
                        <el-form-item label="备注">
                            <el-input v-model="regInfo.hcExt" type="textarea" placeholder="请输入" rows="7"/>
                        </el-form-item>
                    </div>
                </div>

                <!-- 温度 -->
                <div class="table-row"  >
                    <div class="table-cell">
                        <el-form-item label="温度">
                            <el-input v-model="regInfo.fever" style="width: 220px" placeholder="温度" >
                                <template #append>℃</template>
                            </el-input>
                        </el-form-item>
                    </div>
                </div>

                <!-- 特殊疾病 -->
                <div class="table-row"  >
                    <div class="table-cell">
                        <el-form-item label="特殊疾病">
                            <el-input
                                v-model="regInfo.specialRemarks"
                                rows="7"
                                type="textarea"
                                placeholder="请输入"
                            />
                        </el-form-item>
                    </div>
                </div>

                <!-- 结束时间 -->
                <div class="table-row"  >
                    <div class="table-cell">
                        <el-form-item label="诊疗结束时间">
                            <el-date-picker
                                v-model="regInfo.eDate"
                                type="datetime"
                                placeholder="结束时间"
                                format="YYYY-MM-DD HH:mm:ss"
                                value-format="YYYY-MM-DD HH:mm:ss"
                            />
                        </el-form-item>
                    </div>
                </div>
            </div>

            <div style="margin: 20px 0px;"></div>

            <!-- 体检信息 -->
            <el-card style="max-width: 100%;">
                <template #header>
                    <div class="medical-title" style="color: #FFF;">
                        <span>体检信息</span>
                    </div>
                </template>

                <template #default>
                    <div class="medical">
                        <el-row>
                            <el-col :sm="12" :xs="24">
                                <el-form-item label="身高">
                                    <el-input v-model="regInfo.physicalExamination.bodyHeight" style="width: 240px" placeholder="身高" type="number">
                                        <template #append>cm</template>
                                    </el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :sm="12" :xs="24">
                                <el-form-item label="体重">
                                    <el-input v-model="regInfo.physicalExamination.bodyWeight" style="width: 240px" placeholder="体重" type="number">
                                        <template #append>Kg</template>
                                    </el-input>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <!-- 裸眼视力 -->
                        <el-row>
                            <el-col :sm="12" :xs="24">
                                <el-form-item label="左眼裸眼视力">
                                    <el-input v-model="regInfo.physicalExamination.leftEye" style="width: 240px" placeholder="左眼裸眼视力" />          
                                </el-form-item>
                            </el-col>
                            <el-col :sm="12" :xs="24">
                                <el-form-item label="右眼裸眼视力">
                                    <el-input v-model="regInfo.physicalExamination.rightEye" style="width: 240px" placeholder="右眼裸眼视力" />          
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <!-- 矫正视力 -->
                        <el-row>
                            <el-col :sm="12" :xs="24">
                                <el-form-item label="左眼矫正视力">
                                    <el-input v-model="regInfo.physicalExamination.leftEyeCorrected" style="width: 240px" placeholder="左眼矫正视力" />          
                                </el-form-item>
                            </el-col>
                            <el-col :sm="12" :xs="24">
                                <el-form-item label="右眼矫正视力">
                                    <el-input v-model="regInfo.physicalExamination.rightEyeCorrected" style="width: 240px" placeholder="右眼矫正视力" />          
                                </el-form-item>
                            </el-col>
                        </el-row>

                        <!-- 屈光度数 -->
                        <el-row>
                            <el-col :sm="12" :xs="24">
                                <el-form-item label="屈光度数">
                                    <el-input v-model="regInfo.physicalExamination.eyeDiopter" style="width: 240px" placeholder="屈光度数" />          
                                </el-form-item>
                            </el-col>
                            <el-col :sm="12" :xs="24">
                                <el-form-item label="球镜度数">
                                    <el-input v-model="regInfo.physicalExamination.eyeSphericalEquivalent" style="width: 240px" placeholder="球镜度数" />          
                                </el-form-item>
                            </el-col>
                        </el-row>

                        <!-- 柱镜度数 -->
                        <el-row>
                            <el-col :sm="12" :xs="24">
                                <el-form-item label="柱镜度数">
                                    <el-input v-model="regInfo.physicalExamination.eyeCylindrical" style="width: 240px" placeholder="柱镜度数" />          
                                </el-form-item>
                            </el-col>
                            <el-col :sm="12" :xs="24">
                                <el-form-item label="轴位（散光方向）">
                                    <el-input v-model="regInfo.physicalExamination.eyeAxis" style="width: 240px" placeholder="轴位（散光方向）" />          
                                </el-form-item>
                            </el-col>
                        </el-row>

                    </div>
                </template>

                

                <template #footer>
                    <div class="medical-footer">
                        <span>学生健康体检信息</span>
                    </div>
                </template>
            </el-card>

            <div style="margin: 20px 0px;"></div>
            <el-form-item>
                <el-button type="primary" @click="onSubmit(regRuleFormRef)">保存</el-button>
            </el-form-item>
        </el-form>

        <div style="margin: 20px 0px;"></div>


        <!-- 家长信息 -->
        <el-card style="max-width: 100%;">
            <template #header>
                <div class="ps-title">
                    <span>家长信息</span>
                </div>
            </template>

            <template #default>
                <div class="ps">
                    <div>
                        紧急联系人：      {{ regInfo.emergContact1 }} ( {{ regInfo.emerg1Rel }} )   {{ regInfo.emergPhone1 }}
                    </div>
                    <div>
                        紧急联系人：      {{ regInfo.emergContact2 }} ( {{ regInfo.emerg2Rel }} )   {{ regInfo.emergPhone2 }}
                    </div>
                </div>
                
            </template>

            <template #footer>
                <div class="ps-footer">信息来自PowerSchool</div>
            </template>
        </el-card>

    </div>



    <el-dialog v-model="dialogTableVisible" title="历史挂号记录" width="90%" size="small" >
        <el-table :data="gridData">
            <el-table-column property="sDate" label="挂号时间" width="160" />
            <el-table-column property="place" label="地点" width="150" :formatter="formatPlace"/>
            <el-table-column property="symNo" label="就诊原因" width="180" :formatter="formatGroups" />
            <el-table-column property="wayNoSplit" label="处理方式" width="180" :formatter="formatWays"/>
            <el-table-column property="hcExt" label="备注"/>
        </el-table>
    </el-dialog>

</template>

<script setup>
import { onMounted, reactive, ref, onBeforeUnmount } from 'vue';
import { useRouter } from 'vue-router'
import useRegUserStore from '@/stores/registersUserStore'
import useSystemInitStore from '@/stores/init'
import { useDateFormat } from '@vueuse/core'
import { getEmergContact, updateInfo } from '@/api/registers'
import { ElNotification } from 'element-plus'
import { ElMessage } from 'element-plus'
import { getHistoryList } from '@/api/registers'

const router = useRouter()
const regRuleFormRef = ref()
const dialogTableVisible = ref(false)

const gridData = ref([])

const openHistory = () => {
    dialogTableVisible.value = true
    getHistory()
}

const getHistory = () => {
    if(regInfo.sno) {
        const guestbookForm = reactive({
            page: 1,
            size: 30,
            tel: '',
            name: '',
            stu: regInfo.sno,
            faculty: '',
            time: '',
            sTime: '',
            eTime: ''
        })
        getHistoryList(guestbookForm).then(res => {
            if ( res.code == 200 ) {
                gridData.value = res.data.rows
                gridData.value = gridData.value.filter(e => e.hcNo != regInfo.hcNo)
                // totalData.value = res.data.total
                // loading.value = false
            } else {
                ElMessage.error('数据加载失败。')
            }
            
        })
    }
    
}

// 格式化地点
const formatPlace = (row, column, cellValue) => {
    return systemInitStore.places.find(e => e.pno == cellValue).pname
}

// 格式化就诊原因
const formatGroups = (row, column, cellValue) => {
    let gnos = cellValue.split('^')
    let gp1 = systemInitStore.groups.children.find(e => e.id == gnos[1]);
    if(gp1) {
        let gp2 = gp1.children.find(e => e.id == gnos[2]);
        let pName = '';
        if(row.poNo) {
            let po = systemInitStore.positions.find(e => e.poNo == row.poNo);
            return gp2.gname  + ' - ' + po.poName;
        }
        return gp2.gname + pName;
    }
    return '';
}

// 格式化处理方式
const formatWays = (row, column, cellValue) => {
    let ways = cellValue.split(',')
    let wayNames = ''
    ways.forEach(e => {
        let way = systemInitStore.ways.find(e2 => e2.wayNo == e)
        if(way) {
            if(wayNames) { wayNames += ',' }
            wayNames += way.wayName
        }
    })
    return wayNames
}

/// 就诊原因
const onSubmit = (formRef) => {
    formRef.validate( (valid, fields) => {
        if(valid) {
            if(regInfo.groups1 && regInfo.groups2) {
                regInfo.symNo = '02^'+regInfo.groups1+'^'+regInfo.groups2
            }
            if(regInfo.ways.length > 0) {
                regInfo.wayNo = ''
                regInfo.ways.forEach(e=> {
                    if(regInfo.wayNo) { regInfo.wayNo += '^'}
                    regInfo.wayNo += e
                })
            }
            console.log(regInfo)
            // return false
            updateInfo(regInfo).then(res => {
                /// 清除缓存
                regUserStore.$reset()
                if ( res.code == 200 ) {
                    ElNotification({
                        title: '保存成功',
                        type: 'success',
                    })
                    router.push({path: '/records', replace: true})
                } else {
                    ElMessage.error('保存失败。')
                    router.push({path: '/records', replace: true})
                }
            })
            
            
        }

    })
}

/// 挂号信息
const regUserStore = useRegUserStore()

/// 系统信息
const systemInitStore = useSystemInitStore()

onBeforeUnmount(() => {
    regUserStore.$reset()
})

onMounted(() => {
    if(!regUserStore.regInfo || !regUserStore.regInfo.hcNo) {
        router.push({path: '/records', replace: true})
        return;
    } else {
        loadEmergContact()
        loadStuInfo()
    }
    
})

const loadStuInfo = () => {
    regInfo.hcNo = regUserStore.regInfo.hcNo
    regInfo.sno = regUserStore.regInfo.sno
    regInfo.snameC = regUserStore.regInfo.snameC
    regInfo.clscode = regUserStore.regInfo.clscode
    regInfo.eduSystem = regUserStore.regInfo.eduSystem
    regInfo.gender = regUserStore.regInfo.gender
    regInfo.sDate = regUserStore.regInfo.sDate
    regInfo.eDate = regUserStore.regInfo.eDate

    /// 处理方式:ways
    if(regUserStore.regInfo.wayNoSplit) {
        regInfo.ways = regUserStore.regInfo.wayNoSplit.split(',')
        if(regInfo.ways.find(i => i == '05')) {
            isTake.value = true
            regInfo.takeDate = regUserStore.regInfo.takeDate
        }
    }

    /// 地点
    regInfo.place = regUserStore.regInfo.place
    
    /// 意外伤害原因
    regInfo.causeNo = regUserStore.regInfo.causeNo
    
    // 就诊原因
    regInfo.symNo = regUserStore.regInfo.symNo
    if(regInfo.symNo) {
        const selectItems = systemInitStore.groups.children.find(item => item.id === regInfo.symNo.split('^')[1])
        cItems2.value = selectItems.children
        regInfo.groups1 = regInfo.symNo.split('^')[1]
        regInfo.groups2 = regInfo.symNo.split('^')[2]
    } else {

    }

    // 受伤部位
    if(regUserStore.regInfo.poNo && '00' != regUserStore.regInfo.poNo) {
        showcItems.value = true
        regInfo.poNo = regUserStore.regInfo.poNo
    }

    // 体温
    regInfo.fever = regUserStore.regInfo.fever
    
    
    regInfo.hcExt = regUserStore.regInfo.hcExt
    
    regInfo.physicalExamination = regUserStore.regInfo.physicalExamination || {
        bodyHeight: '',
        bodyWeight: '',
        leftEye: '',
        rightEye: '',
        leftEyeCorrected: '',
        rightEyeCorrected: '',
        eyeDiopter: '',
        eyeSphericalEquivalent: '',
        eyeCylindrical: '',
        eyeAxis: '',
    }
    
}

/// 加载学生家长联系人数据
const loadEmergContact = () => {
    getEmergContact({stuNo: regUserStore.regInfo.sno}).then(res => {
        if ( res.code == 200 ) {
            regInfo.emerg1Rel = res.data.emerg1Rel
            regInfo.emerg2Rel = res.data.emerg2Rel
            regInfo.emergContact1 = res.data.emergContact1
            regInfo.emergContact2 = res.data.emergContact2
            regInfo.emergPhone1 = res.data.emergPhone1
            regInfo.emergPhone2 = res.data.emergPhone2
        } else {
            ElMessage.error('数据加载失败。')
        }
    })
}

const cItems2 = ref([])
const showcItems = ref(false)
const onChange1 = (v) => {

    if(v == 4) { /// 当选择ID为4 则显示后面的数据
        showcItems.value = true
    } else {
        showcItems.value = false
    }

    regInfo.groups3 = ''
    regInfo.groups2 = ''

    const items = systemInitStore.groups.children;
    const selectItems = items.find(item => item.id === v)
    if(selectItems.children) {
        cItems2.value = selectItems.children
    } else {
        cItems2.value = []
    }
}

/// 带离时间
const isTake = ref(false)
const onCheckWays = (v) => {
    if ('05' == v.find(i => i == '05')) {
        if('' == regInfo.takeDate) {
            regInfo.takeDate = useDateFormat(new Date(), 'YYYY-MM-DD HH:mm:ss').value
        }
        
        isTake.value = true
    } else {
        isTake.value = false
    }
}

const regInfo = reactive({
    hcNo: '',
    eduSystem: '', 
    sno: '', 
    snameC: '', 
    clscode: '', 
    gender: '', 
    sDate: '',
    eDate: '',  /// 结束时间
    place: '',  /// 受伤地点
    symNo: '',  /// 就诊原因
    wayNo: '',   /// 处理方式
    causeNo: '',   /// 伤害原因
    hcExt: '',   /// 备注
    seePlace: '01',  /// 就诊科室
    fever: '', /// 身体温度
    poNo: '',  /// 受伤部位
    takeDate: '', // 离开时间


    
    ways: [],
    groups1: '',
    groups2: '',


    emerg1Rel: '',
    emerg2Rel: '',
    emergContact1: '',
    emergContact2: '',
    emergPhone1: '',
    emergPhone2: '',
    physicalExamination: {
        bodyHeight: '',
        bodyWeight: '',
        leftEye: '',
        rightEye: '',
        leftEyeCorrected: '',
        rightEyeCorrected: '',
        eyeDiopter: '',
        eyeSphericalEquivalent: '',
        eyeCylindrical: '',
        eyeAxis: '',
    }
})


</script>

<style lang="scss" >
.fillinfo-box {
    padding: 20px;
    height: calc(100vh - 95px);
    width: calc(100% - 40px);
    .table{
        font-size: 13px;
        display: table;
        width: 100%;
        background-color: var(--el-bg-color-page);
        .table-row {
            display: table-row;
            .table-cell {
                display: table-cell;
                border: 1px solid;
                border-color: var(--el-border-color);
                padding: 8px;
                &.table-title{
                    width: 155px;
                    // background-color: #f3f2f2; 
                    text-align: right;
                }
                .el-form-item {
                    margin-bottom: 8px; 
                }
            }
            
        }
    }

    .el-card {
        .el-card__header {
            padding: 0px;
            //padding: calc(var(--el-card-padding) - 10px) var(--el-card-padding);
            color: #9d9d9d;
        }
        .el-card__header .medical-title {
            background-color: #FF7D00;
            padding: calc(var(--el-card-padding) - 10px) var(--el-card-padding);
        }
        .el-card__header .ps-title {
            background-color: #ffffdc;
            padding: calc(var(--el-card-padding) - 10px) var(--el-card-padding);
        }
        .el-card__body {
            padding: 0px;
            background-color: #fffff0;
            line-height: 30px;
            font-size: 12px;
        }
        // 体格检查
        .el-card__body .medical {
            padding: 20px;
            background-color: #fdf3e3;
        }

        // PS信息
        .el-card__body .ps {
            padding: 20px;
        }

        .el-card__footer {
            font-size: 12px;
            padding: 0px;
            color: #cccccc;
        }

        .el-card__footer .medical-footer {
            background-color: #fdf3e3;
            padding: calc(var(--el-card-padding) - 10px) var(--el-card-padding);
        }

        .el-card__footer .ps-footer {
            background-color: #fffff0;
            padding: calc(var(--el-card-padding) - 10px) var(--el-card-padding);      
        }
    }
}
</style>
